package com.linchong.concurrency.chapter6;

/**
 * @Author:linchong
 * @CreateTime:2020-01-06 21:29
 * @Description: 思路：执行线程中设置runner线程，并将runner线程设置为执行线程的守护线程
 * <p>
 * 之后想办法让执行线程中断即可。
 */
public class ThreadService {

	private Thread excuteThread;

	private boolean finished = false;

	/**
	 * 异步任务
	 *
	 * @param task
	 */
	public void excute(Runnable task) {
		excuteThread = new Thread() {
			@Override
			public void run() {
				Thread runner = new Thread(task);
				runner.setDaemon(true);
				runner.start();
				try {
					runner.join();
					finished = true;
				} catch (InterruptedException e) {
				}
			}
		};
		excuteThread.start();
	}

	public void shutdown(long mills) {
		long currentTime = System.currentTimeMillis();
		while (!finished) {
			if (System.currentTimeMillis() - currentTime >= mills) {
				System.out.println("超时，需要结束");
				excuteThread.interrupt();
				break;
			}
			try {
				excuteThread.sleep(1);
			} catch (InterruptedException e) {
				System.out.println("执行线程被打断!");
				break;
			}
		}
		finished = false;
	}

}
